import React, { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { useModel } from 'umi';
// import StatementToolBar from "./components/StatementToolBar";
import "./index.less"
import { throttle } from "lodash";
import StatementToResetMonth from "./components/StatementToResetMonth";
import ReportDataGrid from "./components/ReportDataGrid";

import { EntrySynchronizationMethod, intl } from '@/utils';
import "./index.less"
import { CpasIcon, DevToolBar } from '~/public/cpas-ui';

import { Item } from 'devextreme-react/toolbar';
import { SelectBox, TextBox } from 'devextreme-react';
import { getAccountInfo, reCalReportItemsData } from './service';
import notify from "devextreme/ui/notify";
import { Spin } from "antd";
import { msgInfo } from "@/utils/msg";


const StatementData = () => {

  const { initialState } = useModel('@@initialState');
  const { dbname, zcbfid, XMType } = initialState?.curPart as API.CurPart;
  const { io } = require('socket.io-client');

  const { username, usercode, } = initialState?.curUser as API.CurUser;
  const userInfoStr = window.localStorage.cpasUserInfo;
  const userInfo = JSON.parse(userInfoStr);
  const password = window.main.cryptoUtil(userInfo.aesPassword);
  const sessionParams = JSON.parse(window.sessionStorage.electronParams);
  const { sjxmbh, ZcbfID, sjnd } = sessionParams.params;
  const [loadingTimerId, setLoadingTimer] = useState<any>(null);

  const TreeList = useRef<any>();
  const [accountYear, setAccountYear] = useState<string>('');
  const [accountYearData, setAccountYearData] = useState<any[]>([]);
  const [TextValue, setTextValue] = useState<any>('');
  const ToResetRef = useRef<any>();
  const [changeTimeData, setChangeTimeData] = useState<string>("");
  const [selDefaultValue, setSelDefaultValue] = useState<any>('');
  const [pageLoading, setPageLoading] = useState(false);


  const Divstyle: React.CSSProperties = {
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'center',
  };
  const Titlestyle: React.CSSProperties = { marginRight: '8px' };

  // 浏览器的高度 默认设置为0；
  // const [height, setHeight] = useState(0);
  const [resizeWidth, setResizeWidth] = useState(0);
  const accountYearRef = useRef<any>();


  const resizeUpdate = (e: any) => {
    // 通过事件对象获取浏览器窗口的高度
    // const h = e.target.innerHeight;
    const w = e.target.innerWidth;
    // setHeight(h);
    setResizeWidth(w);
  };
  const changeTimes = () => {
    setChangeTimeData(`${new Date().getTime()}`);
  }

  const getFetchData = async () => {
    const auditAdjustId: any = window.localStorage.getItem(`selectDefaultTool_${dbname}`);
    const tempYear = JSON.parse(auditAdjustId)?.tabledataId ?? sjnd;
    let findTemp = -2;
    const res: any = await getAccountInfo({ dbname });
    if (res.success) {
      findTemp = res.data.findIndex((item: any) => {
        return tempYear === item.Data_ID
      });
      const tempIndex = findTemp >= 0 ? findTemp : 0;
      const displayNames = res.data[tempIndex]?.displayName;

      setSelDefaultValue(displayNames);
      const DataId = res.data[tempIndex]?.Data_ID;
      res.data.forEach((item: any, index: any) => {
        item.index = index
        return item
      });

      setAccountYearData(res.data);
      const DataIdByMonth = res.data[findTemp]?.byMonth;
      setTextValue(`${DataIdByMonth}`);
      accountYearRef.current = DataId;
      setAccountYear(DataId);
      changeTimes();
    }
  }

  const dataRefresh = (r: boolean) => {
    if (r) {
      TreeList.current.Refresh();
      TreeList.current.TabsState('0');
      setPageLoading(false);
    }
  };


  useEffect(() => {
    // 页面刚加载完成后获取浏览器窗口的大小
    // const h = window.innerHeight;
    const w = window.innerWidth;
    // setHeight(h);
    setResizeWidth(w);
    // 页面变化时获取浏览器窗口的大小 
    window.addEventListener('resize', resizeUpdate);
    getFetchData();
    return () => {
      // 组件销毁时移除监听事件
      window.removeEventListener('resize', resizeUpdate);
    }
  }, []);

  useEffect(() => {
    const cpasApiUrl = localStorage.getItem("cpasApiUrl");
    const apiUrl = cpasApiUrl && cpasApiUrl.includes("cpasApi") ? cpasApiUrl.replace("/cpasApi", "") : cpasApiUrl;
    const socket = io(apiUrl, {
      connectionStateRecovery: {
        // the backup duration of the sessions and the packets
        maxDisconnectionDuration: 2 * 60 * 1000,
        // whether to skip middlewares upon successful recovery
        skipMiddlewares: true,
      },
      auth: {
        name: "notes"
      }
    });
    socket.on('connect', () => {
      const engine = socket.io.engine;
      console.log('socket connect: ', engine.transport.name); // in most cases, prints "polling"
      engine.on("close", (reason: any) => {
        // called when the underlying connection is closed
        console.log('@@@ socket close: ', reason);
      });
    });

    // either by directly modifying the `auth` attribute
    socket.on("connect_error", () => {
      console.log("@@@ connect_error 连接错误");
    });

    socket.io.on("reconnect_attempt", () => {
      console.log("@@@ reconnect_attempt 尝试重新连接");
    });

    socket.io.on("reconnect", () => {
      console.log("@@@ reconnect 尝试重新连接");
    });

    socket.on("disconnect", (reason: any) => {
      // ...
      console.log("@@@ disconnect 断开连接", reason);
    });

    socket.onAny((eventName: any, ...args: any) => {
      console.log(`@@@ on refresh onAny: ${eventName}`, args);
    });
    socket.on('notesSyncState', (msg: any) => {
      const res = msg ? JSON.parse(msg) : {};
      const tempArgs = res?.args || {};
      console.log('@@@ on refresh ui event: ', res, tempArgs);
      setPageLoading(false);
      if (res) {
        if (res.ok && tempArgs?.tag === "BBJCSJ1") {
          clearInterval(loadingTimerId);
          getFetchData();
          dataRefresh(true);
          notify('同步数据成功！', 'success', 2000);
        } else {
          notify('同步数据失败！', 'error', 2000);
        }
      }
    });
    return () => {
      clearInterval(loadingTimerId);
      socket.close();
    }
  }, [loadingTimerId]);



  const changeCategoryMenuOptions = {
    items: [
      {
        icon: 'iconfont icon-ellipsis',
        items: [
          // {
          //     ID: "0",
          //     icon: 'iconfont icon-sunyikemushangqishuweihu',
          //     text: '损益科目上期数维护',
          // },
          {
            ID: '1',
            icon: 'iconfont icon-zhongsuanbaobiaoxiangmushuju',
            text: '重算报表项目数据',
          },
          // {
          //     ID: "2",
          //     icon: 'iconfont icon-fujiagongneng',
          //     text: '保存为财务报告体系模板',
          // },
          {
            ID: '3',
            icon: 'iconfont icon-tongbu',
            text: '同步',
          },
        ],
      },
    ],
    onItemClick: async (e: any) => {
      switch (e.itemData.ID) {
        case '0':
          {
            console.log(1);
          }
          break;
        case '1':
          {
            const res = await reCalReportItemsData({
              dbname,
              Data_ID: accountYearRef.current,
              editUser: username,
              isRecalTZ: true,
            });
            if (res.success) {
              notify("重新计算报表项目数据成功", 'Success', 2000)
              dataRefresh(true);
            }
          }
          break;
        case '3':
          setPageLoading(true)
          console.log('@@@  同步');

          const BusID = "报表项目基础数据"
          EntrySynchronizationMethod({
            usercode, password, zcbfid, BusID, tag: "BBJCSJ1"
          });
          const timer = setTimeout(() => {
            notify("未收到同步结果", "error")
            setPageLoading(false)
          }, 120000);
          setLoadingTimer(timer);
          break;
      }
    },
  };


  const changeMenuOptions = {
    items: [
      {
        icon: 'iconfont icon-ellipsis',
        items: [
          // {
          //     ID: "0",
          //     icon: 'iconfont icon-sunyikemushangqishuweihu',
          //     text: '损益科目上期数维护',
          // },
          {
            ID: '1',
            icon: 'iconfont icon-zhongsuanbaobiaoxiangmushuju',
            text: '重算报表项目数据',
          },
          // {
          //     ID: "2",
          //     icon: 'iconfont icon-fujiagongneng',
          //     text: '保存为财务报告体系模板',
          // },
          // {
          //   ID: '3',
          //   icon: 'iconfont icon-tongbu',
          //   text: '同步',
          // },
        ],
      },
    ],
    onItemClick: async (e: any) => {
      switch (e.itemData.ID) {
        case '0':
          {
            console.log(1);
          }
          break;
        case '1':
          {
            const res = await reCalReportItemsData({
              dbname,
              Data_ID: accountYearRef.current,
              editUser: username,
              isRecalTZ: true,
            });
            if (res.success) {
              notify("重新计算报表项目数据成功", 'Success', 2000)
              dataRefresh(true);
            }
          }
          break;
        // case '3':
        //   const BusID = "报表基础数据"
        //   EntrySynchronizationMethod({
        //     usercode, password, zcbfid, BusID
        //   })
        //   break;
      }
    },
  };



  const onSelectionChangeds = (e: any) => {
    if (TreeList.current) {
      const v: any = window.localStorage.getItem(`selectDefaultTool_${dbname}`);
      let selectDefaultIDs = JSON.parse(v);
      selectDefaultIDs = { ...selectDefaultIDs, tabledataId: e.selectedItem.Data_ID };
      // 本地存储 持久化数据
      window.localStorage.setItem(`selectDefaultTool_${dbname}`, JSON.stringify(selectDefaultIDs));
      getFetchData();
    }


  };

  function ContentTextValue(r: string) {
    setTextValue(r);
  };

  // 模糊搜索
  const inputSearch = (content: any) => {
    TreeList.current.TreeListRef().instance.searchByText(content || "");
  }
  const throttleSearch = throttle(inputSearch, 300);
  const getInputValue = (e: any) => {
    const { event } = e;
    throttleSearch(event.target.value);
  }


  return (
    <div>
      <Spin spinning={pageLoading}>
        <div style={{ width: "100%", height: "calc(100vh - 50px)", overflow: "hidden" }}>
          <div style={{ width: "100%", height: "36px", }}>
            <DevToolBar.Default className="ItemStyle">
              <Item location="before" >
                {useMemo(() => {
                  if (selDefaultValue && TextValue) {
                    return <div style={Divstyle}>
                      <div style={Divstyle}>
                        <div style={Titlestyle}>{intl('report.subject.account', '账套:')}</div>
                        <SelectBox
                          width={resizeWidth <= 1467 ? 100 : 200}
                          dataSource={accountYearData}
                          displayExpr='displayName'
                          valueExpr='displayName'
                          defaultValue={selDefaultValue}
                          onSelectionChanged={onSelectionChangeds}
                          dropDownOptions={{
                            width: '350px'
                          }} />
                      </div>
                      <div style={{ ...Divstyle, paddingLeft: 20 }}>
                        <div style={Titlestyle}>{intl('report.subject.EndMonth', '截止月份:')}</div>
                        <TextBox
                          style={{ position: 'relative' }}
                          width={90}
                          // width={resizeWidth < 1040 ? 50 : 80}
                          value={TextValue}
                          defaultValue={TextValue}
                          placeholder="选择..."
                        >
                          <span style={{ position: 'absolute', right: '5px', top: '5px', zIndex: '2' }}>
                            <CpasIcon
                              type="icon-yuefenzhongzhi"
                              onClick={async () => {
                                ToResetRef.current.show(
                                  {
                                    args: { title: '重新设置截止月份' },
                                    OkCallback: () => {
                                      dataRefresh(true);
                                    }
                                  }, `${TextValue}`,
                                );
                              }}
                            />
                          </span>
                        </TextBox>
                      </div>
                    </div>
                  }
                  return <div>loading...</div>

                }, [changeTimeData, TextValue])}
              </Item>
              <Item location="before">
                <div className="Icon_Hover_StyleBtn"
                  onClick={() => {
                    // const Parameter = `UserCode=${usercode} UserPwd=${password} ProjectCode=${sjxmbh} ZcbfID=${ZcbfID} Functions=RIM_110 FunParameters="Data_ID=${sjnd}" `;
                    // window.location.href = `cpas://OpenLocalFile/?fileName=./UFCPAS4.exe&params=${Parameter}&workDir=./SysBPL`;&workDir=./SysBPL   RIM_104
                    msgInfo(`正在打开 报表项目对应,请稍候...`);
                    const sessionParams = JSON.parse(window.sessionStorage.electronParams);
                    const { sjxmbh, ZcbfID } = sessionParams.params;
                    window.location.href = `cpas://OpenLocalFile/?fileName={UFCPAS4_PATH}/UFCPAS4.exe&params=UserCode={UserCode} UserPwd={UserPwd} ProjectCode=${sjxmbh} ZcbfID=${ZcbfID} Functions=RIM_104 FunParameters="Data_ID=${sjnd}"`;
                  }}>
                  <CpasIcon
                    type="icon-baobiaoxiangmuduiying1"
                    fontSize={18}
                  />
                  <span style={{ marginLeft: '5px' }} >
                    报表项目对应
                  </span>
                </div>
              </Item>
              <Item location="after">
                <div>
                  <TextBox
                    onInput={(e: any) => getInputValue(e)}
                    className="TextBoxButtons_Style"
                    buttons={[
                      {
                        location: 'before',
                        name: 'search',
                        options: {
                          icon: 'iconfont icon-search',
                          disabled: true,
                        },
                      },
                    ]}
                  />
                </div>
              </Item>
              <Item location="after">
                <div style={Divstyle}>
                  <div className="IconRefresh_Style" onClick={() => {
                    dataRefresh(true);
                  }}>
                    <CpasIcon
                      type="icon-refresh"
                      fontSize={16}
                    />
                  </div>
                </div>
              </Item>
              <Item
                widget="dxMenu"
                location="after"
                options={XMType === '联机审计项目' ? changeCategoryMenuOptions : changeMenuOptions}
                cssClass="AgainMenu"
              />
            </DevToolBar.Default>
          </div>
          {useMemo(() => {
            return <StatementToResetMonth ref={ToResetRef} Content={ContentTextValue} AccountDataID={accountYear ? accountYear : accountYearRef.current} />
          }, [accountYear])}
          <div style={{ width: "100%", height: "calc(100% - 45px)", borderTop: "1px solid #ebe7e7", marginTop: "6px" }}>
            {useMemo(() => {
              return <ReportDataGrid ref={TreeList} data_ID={accountYear ? accountYear : accountYearRef.current} />
            }, [accountYear])}
          </div>

        </div>
      </Spin>
    </div>
  )
};

export default StatementData;
